package com.shiku.mianshi.controller;

import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.ex.ServiceException;
import cn.xyz.commons.utils.DateUtil;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.mianshi.opensdk.entity.SkOpenApp;
import cn.xyz.mianshi.opensdk.until.SkOpenUtil;
import cn.xyz.mianshi.utils.SKBeanUtils;
import cn.xyz.mianshi.vo.Helper;
import cn.xyz.mianshi.vo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.query.Query;
import org.springframework.web.bind.annotation.*;

import java.net.URL;

import static cn.xyz.mianshi.utils.SKBeanUtils.getDatastore;

@Slf4j
@RestController
@Api(value="OpenUserController",tags="开放平台接口_用户端")
@RequestMapping(value = "/useropen")
public class OpenUserController  extends AbstractController{

    public Class<SkOpenApp> getEntityClass() {
        return SkOpenApp.class;

    }
    /**
     * 添加群助手

     * @return
     */
    @ApiOperation("添加群助手")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "link",value = "url地址" ,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "name",value = "标题" ,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "desc",value = "描述" ,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "iconUrl",value = "图标" ,dataType = "String"),
    })
    @RequestMapping(value = "/addHelper",method = {RequestMethod.POST,RequestMethod.GET})
    public JSONMessage addHelper(@RequestParam(defaultValue="") String link,
                                 @RequestParam(defaultValue="") String name,
                                 @RequestParam(defaultValue="") String desc,
                                 @RequestParam(defaultValue="") String iconUrl
                                 ){
        try {
            logger.info("[ww]:addHelper  link="+link);
            if(link.length() ==0 )
            {
                return JSONMessage.failure("error");
            }
            try {
                URL requestUrl = new URL(link);
                String webUrl = requestUrl.getHost();
                logger.info("[ww]:webUrl="+webUrl);
            } catch (Exception e) {
                throw new ServiceException(KConstants.ResultCode.ParamsAuthFail);
            }
            User user = SKBeanUtils.getUserManager().getUser(ReqUtil.getUserId());
            Query<SkOpenApp> query = getDatastore().createQuery(getEntityClass());

            SkOpenApp entity = new SkOpenApp();
            entity.setAccountId( String.valueOf(user.getUserId()));
            entity.setCreateTime(DateUtil.currentTimeSeconds());
            entity.setModifyTime(DateUtil.currentTimeSeconds());
            entity.setAppName(name);
            entity.setAppUrl(link);
            entity.setAppImg(iconUrl);
            entity.setAppsmallImg(iconUrl);
            entity.setIsAuthShare((byte)0);
            entity.setIsAuthLogin((byte)0);
            entity.setIsAuthPay((byte)0);
            entity.setIsGroupHelper((byte)1);
            entity.setStatus((byte)1);
            entity.setCallbackUrl("");
            entity.setAppType((byte)2);
            entity.setAppId(SkOpenUtil.getAppId());
            entity.setAppSecret(SkOpenUtil.getAppScrect(entity.getAppId()));

            Key<SkOpenApp> save = getDatastore().save(entity);


            Helper  _helper  = new Helper();
            _helper.setOpenAppId(save.getId().toString());
            _helper.setLink(link);
            _helper.setName(name);
            _helper.setDesc(desc);
            _helper.setIconUrl(iconUrl);
            _helper.setOwerUserID(ReqUtil.getUserId());

            _helper.setDeveloper(user.getNickname());
            _helper.setIsOpen(0);
            _helper.setType(2);

            logger.info("[ww]:addHelper,helper="+_helper.getLink());
            SKBeanUtils.getOpenAppManage().addHelper(_helper);
            return JSONMessage.success();
        } catch (Exception e) {
            return JSONMessage.failureByException(e);
        }
    }


    @ApiOperation("修改群助手")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "id",value = "id" ,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "link",value = "url地址" ,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "name",value = "标题" ,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "desc",value = "描述" ,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "iconUrl",value = "图标" ,dataType = "String"),
    })
    @RequestMapping(value = "/updateHelper",method = {RequestMethod.POST,RequestMethod.GET})
    public JSONMessage updateHelper(
                                     @RequestParam(defaultValue="") String id,
                                    @RequestParam(defaultValue="") String link,
                                    @RequestParam(defaultValue="") String name,
                                    @RequestParam(defaultValue="") String desc,
                                    @RequestParam(defaultValue="") String iconUrl){
        try {

            if(link.length() >0 )
            {
                try {
                    URL requestUrl = new URL(link);
                } catch (Exception e) {
                    throw new ServiceException(KConstants.ResultCode.ParamsAuthFail);
                }
            }

            Helper  _helper  = new Helper();
            _helper.setId(new ObjectId(id));
            if(link.length()>0)
            {
                _helper.setLink(link);
            }
            if(name.length()>0)
            {
                _helper.setName(name);
            }
            if(desc.length()>0)
            {
                _helper.setDesc(desc);
            }
            if(iconUrl.length()>0)
            {
                _helper.setIconUrl(iconUrl);
            }

            SKBeanUtils.getOpenAppManage().updateHelper(_helper);
            return JSONMessage.success();
        } catch (Exception e) {
            return JSONMessage.failureByException(e);
        }
    }
    /**
     * 删除群助手
     * @param id
     * @return
     */
    @ApiOperation("删除群助手")
    @ApiImplicitParam(paramType = "query",name = "id",value = "编号",dataType = "String")
    @RequestMapping(value = "/deleteHelper",method = {RequestMethod.POST,RequestMethod.GET})
    public JSONMessage deleteHelper(@RequestParam(defaultValue="") String id){
        try {
            SKBeanUtils.getOpenAppManage().deleteHelper(ReqUtil.getUserId(),new ObjectId(id));
            return JSONMessage.success();
        } catch (Exception e) {
            return JSONMessage.failureByException(e);
        }

    }

}

